package com.jt.www.common.service.zqsign.dependency;

import com.jt.www.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @描述：
 * @作者： lux
 * @创建日期： 2018-9-6 17:03
 * @版权： 江泰保险经纪股份有限公司
 */
public class EncryptData {

    public static final Logger log = LoggerFactory.getLogger(EncryptData.class);

    public String encrptData(Map<String,String> map, String private_key){
        String keyValueStr = ZqkjCore.createLinkString(map);
        String signVal= DecryptData.sign(keyValueStr, private_key, "utf-8");
        return signVal;
    }

    public boolean verify(Map<String,String> map,String public_key){
        String sign=map.get("sign_val");
        if(sign==null){
            throw new RuntimeException("签名值为空");
        }
        map.remove("ws_sign_val");
        String content = ZqkjCore.createLinkString(map);
        return DecryptData.verify(content, sign, public_key, "utf-8");
    }


    /**
     * 非对称加密 算法：base64加密，奇偶位，
     * @param encryption
     * @return
     */
    public static String encode(String encryption) {
        if (!StringUtils.isEmpty(encryption)) {
            String base64 = new String(org.apache.commons.codec.binary.Base64.encodeBase64(encryption.getBytes(StandardCharsets.UTF_8)));
            String[] split = base64.split("");
            for (int i = 1; i < split.length; i+= 2) {
                String str = split[i];
                split[i] = split[i-1];
                split[i-1] = str;
            }
            String join = String.join("", split);
            return join + "0";
        }
        return encryption;
    }

    /**
     * 解密
     * @param encryption
     * @return
     */
    public static String decode(String encryption) throws Exception {
        try {
            if (!StringUtils.isEmpty(encryption)) {
                String str = encryption.substring(0, encryption.length() - 1);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < str.length(); i++) {
                    if (i % 2 == 0) {
                        char a = str.charAt(i);
                        char b = str.charAt(i + 1);
                        sb.append(b).append(a);
                    }
                }
                return new String(org.apache.commons.codec.binary.Base64.decodeBase64(sb.toString()), StandardCharsets.UTF_8);
            }else{
                return encryption;
            }
        } catch (Exception e) {
            log.error("解密失败，可能原因：1.入参格式有误，2.参数加密算法有误，解密内容={},errorMsg={}",encryption,e.getMessage(),e);
            throw new ServiceException("数据加密格式有误");
        }
    }

}
